package com.deer.wms.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.company.dao.CompanyMapper;
import com.deer.wms.company.model.Company;
import com.deer.wms.company.model.CompanyCriteria;
import com.deer.wms.company.service.CompanyService;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.system.manage.model.user.UserInfo;
import com.deer.wms.system.manage.service.UserInfoService;
import com.deer.wms.system.manage.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wei
 * @since 2021-07-23
 */
@Service("companyService")
public class CompanyServiceImpl extends SuperServiceImpl<CompanyMapper, Company> implements CompanyService {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public Company findBy(String field, String value) {
        QueryWrapper<Company> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }

    @Override
    public void add(Company company, UserInfo userInfo) {
        this.save(company);
        userInfoService.save(userInfo);
    }

    @Override
    public List<Company> selectCheckedCompanies(CompanyCriteria criteria) {
        QueryWrapper<Company> qw = new QueryWrapper<>();
        qw.eq("audit_state", 1);
        if (StringUtils.isNotEmpty(criteria.getKeyWords())) {
            qw.like("name", criteria.getKeyWords());
        }
        return this.list(qw);
    }

    @Override
    public List<Company> selectNewCompanies(CompanyCriteria criteria) {
        QueryWrapper<Company> qw = new QueryWrapper<>();
        qw.eq("audit_state", 0);
        if (StringUtils.isNotEmpty(criteria.getKeyWords())) {
            qw.like("name", criteria.getKeyWords());
        }
        return this.list(qw);
    }

    @Override
    public void pass(Company company) {
        //修改租户状态
        company.setAuditState(1);
        //修改租户管理员的状态，并赋予角色
        String userAccount = company.getManagerId();
        UserInfo userInfo = userInfoService.findInvalidUserInfoByAccount(userAccount);
        userInfo.setState("normal");
        //分配角色 - 企业管理员
        userRoleService.addUserRole(userInfo.getUserId(), 32);
        userInfoService.updateById(userInfo);
        this.updateById(company);
    }

}
